import React, { useEffect, useMemo, useRef, useState } from 'react'
import { Image, Input, Button, Toast } from 'antd-mobile'
import style from '../message/index.module.css'
function Index() {
  const user_id = 1;
  const server_id = 7788;
  const [list, setList] = useState([]);
  const [message, setMessage] = useState('');
  const refMsg = useRef(null);


  const ws = useMemo(() => {
    return new WebSocket(
      `ws:124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
    );
  }, [])

  useEffect(() => {
    ws.onopen = () => {
      console.log('OK');
      ws.send(JSON.stringify({ type: 'getChatList' }))
    };

    ws.onmessage = (msg) => {
      console.log(msg.data);
      const { data, type } = JSON.parse(msg.data);
      if (type === 'getChatList') {
        setList(data);
      } else if (type === 'AddMessage') {
        setList((prev) => [...prev, data])
      }
    }
  }, [])


  useEffect(() => {
    refMsg.current.scrollIntoView({
      behavior: 'auto'
    })

  }, [list])


  const handSend = () => {
    if (!message.length) return Toast.show('请输入内容')
    ws.send(JSON.stringify({ type: 'AddMessage', data: { user_id, server_id, message } }))
    setMessage.value = 'refMsg'
    setMessage('')
  }
  return (
    <div>


      <div className={style.msgBox}>
        {list.length > 0 && list.map((item, index) => {
          if (item.dir === 1) {
            return (
              <div key={index} className={style.right}>
                <Image className={style.img} style={{ width: '50px', height: '50px', borderRadius: '50%' }} src={item.user_avatar}></Image>
                <div className={style.tit}>{item.message}</div>
              </div>
            )
          }

        })}
        <div ref={refMsg} />
      </div>


      <div className={style.sendBox}>
        <Input
          className={style.inp}
          placeholder='请输入内容'
          value={message}
          onChange={val => {
            setMessage(val)
          }}
        />

        <Button disabled={!message.trim()} onClick={() => handSend()} className={style.btn} color='primary' fill='solid'>
          发送
        </Button>
      </div>

    </div>
  )
}

export default Index
